package Demo;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.net.SocketAddress;
import java.util.Scanner;

public class TcpEchoClient {
     private Socket socket = null;
     public TcpEchoClient(String serverIP, int serverPort) throws IOException {
         socket = new Socket(serverIP, serverPort);
//         socket = new Socket();
//         socket.connect(new InetSocketAddress(serverIP, serverPort));
     }

     public void start() {
         System.out.println("客户端启动!");
         Scanner scanner = new Scanner(System.in);
         try (InputStream inputStream = socket.getInputStream();
              OutputStream outputStream = socket.getOutputStream()) {
             while (true) {
                 System.out.println("请输入要发送的消息:");
                 String request = scanner.nextLine();
                 PrintWriter writer = new PrintWriter(outputStream);
                 writer.println(request);
                 writer.flush();
                 System.out.println("消息已发送!");
                 Scanner responseScanner = new Scanner(inputStream);
                 String response = responseScanner.nextLine();
                 System.out.println("收到服务器的响应:" + response);
             }

         } catch (IOException e) {
             e.printStackTrace();
         }
     }

    public static void main(String[] args) throws IOException {
        TcpEchoClient client = new TcpEchoClient("127.0.0.1", 8080);
        client.start();
    }
}
